package cn.skylark.wcm.controller;


import cn.skylark.wcm.common.util.PasswordHelper;
import cn.skylark.wcm.common.util.ReturnMap;
import cn.skylark.wcm.entity.Resources;
import cn.skylark.wcm.entity.Role;
import cn.skylark.wcm.entity.Tenan;
import cn.skylark.wcm.entity.User;
import cn.skylark.wcm.service.*;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户控制器类
 *
 * @author 武文旭
 * @Date 20180109
 * @since
 */
@RestController
@RequestMapping("/tenans")
public class TenanController {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TenanController.class);
    @Autowired
    TenanService tenanService;
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleResourcesService roleResourcesService;
    @Autowired
    ResourcesService resourcesService;

    /**
     * 获取所有租户信息
     * 业务:通过userid用户所有租户信息
     *
     * @param tenan
     * @param length
     * @param start
     * @return List<Tenan>
     */
    @RequestMapping("/getAllTenan")
    public Map<String, Object> getAllTenan(Tenan tenan, HttpServletRequest request,
                                      @RequestParam(required = false, defaultValue = "1") int start,
                                      @RequestParam(required = false, defaultValue = "10") int length) {
        LOGGER.info("获取所有租户信息开始 租户=" + tenan + "开始页" + start + "条数" + length);
        String searchValue = request.getParameter("search[value]");
        String flag = request.getParameter("flag");
        Map<String, Object> map = new HashMap<>();
        PageInfo<Tenan> pageInfo = tenanService.selectByPage(tenan, flag, searchValue, start, length);
        map.put("recordsTotal", pageInfo.getTotal());
        map.put("recordsFiltered", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        LOGGER.info("获取所有租户信息结束");
        return map;
    }

    /**
     * 新增租户
     * 1、通过前端传过来的租户信息，首先查看租户是否存在
     * 2、如不存在则新增，如存在则提示租户已存在
     *
     * @param tenan 为新增租户的信息
     * @return message做出是否成功的提示信息
     * @Exception e 为数据库是否连接异常
     */
    @RequestMapping(value = "/addTenan")
    public String addTenan(Tenan tenan) {
        LOGGER.info("新增租户开始 租户信息=" + tenan);
        ReturnMap ret = new ReturnMap();
        try {
            LOGGER.info("新增租户的租户名为 tenanname=" + tenan.getTenanname());
            Tenan tenanName = new Tenan();
            tenanName.setTenanname(tenan.getTenanname());
            Integer u = tenanService.selectByTenanname(tenanName);
            if (u > 0) {
                LOGGER.info("新增失败用户已存在");
                ret.setFlg(1);
                ret.setMessage("租户已存在！");
                return ret.ReturnMap();
            }
            tenanService.addTenan(tenan);
            Tenan tenanMessage = tenanService.getTenanByOne(tenan);
            User user = new User();
            user.setTenanid(tenanMessage.getId());
            user.setUsername(tenanMessage.getTenancode());
            PasswordHelper passwordHelper = new PasswordHelper();
            user.setPassword(passwordHelper.encrypt(tenanMessage.getTenancode()));
            user.setAddress("");
            user.setEmail("");
            user.setPhone("");
            user.setSex(1);
            user.setEnable(0);
            user.setDelflg(0);
            userService.addUser(user);
            //增加租户管理员角色
            User userMessage = userService.getUserDataById(user);
            Role role = new Role();
            role.setTenanid(tenanMessage.getId());
            role.setRoledesc("租户管理员");
            roleService.save(role);
            Role roleMessage = roleService.selectByParameter(role);
            userRoleService.save(roleMessage.getId().toString(), userMessage.getId());
            //租户管理员权限角色关系设置
            List<Resources> adminresourcesList = resourcesService.getResourcesListByParentId("1");
            List<String> adminlist = new ArrayList<>();
            for (Resources resourcesId : adminresourcesList) {
                adminlist.add(resourcesId.getId().toString());
            }
            String[] toadminresource = adminlist.toArray(new String[adminlist.size()]);
            roleResourcesService.addRoleResources(roleMessage.getId(), toadminresource);
            //增加租户用户角色
            Role userrole = new Role();
            userrole.setTenanid(tenanMessage.getId());
            userrole.setRoledesc("租户用户");
            roleService.save(userrole);
            Role userroleMessage = roleService.selectByParameter(userrole);
            //租户用户权限角色关系设置
            List<Resources> userresourcesList = resourcesService.getResourcesListByParentId("2");
            List<String> userlist = new ArrayList<>();
            for (Resources resourcesId : userresourcesList) {
                userlist.add(resourcesId.getId().toString());
            }
            String[] touserresource = userlist.toArray(new String[userlist.size()]);
            roleResourcesService.addRoleResources(userroleMessage.getId(), touserresource);
            tenanMessage.setUserid(userMessage.getId());
            tenanService.updateTenan(tenanMessage);
            ret.setFlg(0);
            ret.setMessage("新增租户添加成功！");
            LOGGER.info("新增租户结束");
            return ret.ReturnMap();
        } catch (Exception e) {
            LOGGER.info("异常信息为=" + e);
            e.printStackTrace();
            ret.setFlg(2);
            ret.setMessage("新增租户添加失败！");
            return ret.ReturnMap();
        }
    }

    /**
     * 删除租户
     * 1、将tenan表中delflg值改为1为逻辑删除
     *
     * @param id 为租户id
     * @return 返回message提示
     * @Exception e 数据库连接异常信息
     */
    @RequestMapping(value = "/deleteTenan")
    public String delete(Integer id) {
        ReturnMap ret = new ReturnMap();
        LOGGER.info("删除租户开始 主键=" + id);
        try {
            tenanService.delTenan(id);
            ret.setFlg(0);
            ret.setMessage("删除租户删除成功！");
            LOGGER.info("删除租户结束");
            return ret.ReturnMap();
        } catch (Exception e) {
            LOGGER.info("异常信息为=" + e);
            e.printStackTrace();
            ret.setFlg(2);
            ret.setMessage("删除租户删除失败！");
            return ret.ReturnMap();
        }
    }
}
